﻿hojo.provide('icallcenter.Phone')
hojo.require('hojo.io.script')
hojo.require('icallcenter.hojotools')
hojo.require('icallcenter.stateElement.base')
hojo.require('icallcenter.stateElement.hold')
hojo.require('icallcenter.stateElement.invalid')
hojo.require('icallcenter.stateElement.abate')
hojo.require('icallcenter.stateElement.peerState')
hojo.require('icallcenter.stateElement.link.consultationLink')
hojo.require('icallcenter.stateElement.link.innerLink')
hojo.require('icallcenter.stateElement.link.dialoutLink')
hojo.require('icallcenter.stateElement.link.listenLink')
hojo.require('icallcenter.stateElement.link.normalLink')
hojo.require('icallcenter.stateElement.link.threeWayCallLink')
hojo.require('icallcenter.stateElement.ring.innerRing')
hojo.require('icallcenter.stateElement.ring.normalRing')
hojo.require('icallcenter.stateElement.ring.listenRing')
hojo.require('icallcenter.stateElement.ringring.consultationRinging')
hojo.require('icallcenter.stateElement.ringring.innerRinging')
hojo.require('icallcenter.stateElement.ringring.normalRinging')
hojo.declare('icallcenter.Phone', null, {
  _base: null,
  _peerState: null,
  _invalid: null,
  _abate: null,
  _hold: null,
  _consultationLink: null,
  _innerLink: null,
  _dialoutLink: null,
  _listenLink: null,
  _normalLink: null,
  _threeWayCallLink: null,
  _innerRing: null,
  _normalRing: null,
  _listenRing: null,
  _consultationRinging: null,
  _innerRinging: null,
  _normalRinging: null,
  monitorPeers: [],
  monitorQueues: [],
  monitorServiceNos: [],
  accountCalls: null,
  _isWaitingEvent: false,
  _destroyed: false,
  callObject: {},
  _curChannel: null,
  _otherChannel: null,
  _callId: null,
  iccCount: 0,
  dialoutData: null,
  _isInvestigatting: false,
  _isLooting: false,
  _isCallingOut: false,
  _isSettingbusy: false,
  _isRing: false,
  _handles: [],
  constructor: function (a) {
    var b = this.register('EvtAutoBusyTime', this, 'onAutoBusyTimeChanged')
    this._handles.push(b)
    this._loadConfig(a)
    this._evtXhr = hojo._xhrObj()
    this._waitEvent()
  },
  destroy: function (d) {
    if (!this._destroyed) {
      for (var c in this._handles) {
        this.unregister(this._handles[c])
      }
      this._stopEvent()
      this._exit(this.loginName, d)
      this._destroyed = true
    }
  },
  _loadConfig: function (a) {
    for (var c in a) {
      this[c] = a[c]
    }
  },
  _stopEvent: function () {
    if (this._evtXhr) {
      this._evtXhr.abort()
      this._evtXhr = null
    }
  },
  onRing: function (f, g) {
    this.oldInboundId = this._inboundId
    console.debug('控件onRing返回[callId:%s,remoteId:%s]', f, g)
    this._inboundId = f
  },
  onRemoteRing: function (f, g) {
    console.debug('控件onRemoteRing返回[callId:%s,remoteId:%s]', f, g)
    this._outboundId = f
  },
  onCalloutFail: function (f, h) {
    console.debug('控件CalloutFail返回[callId:%s,cause:%s,inboundid:%s]', f, h, this._inboundId)
    if (this.state == 'stConsulting') {
      if (this._inboundId) {
        sipPhone.ChangeCurrentCall(this._inboundId)
        this._changeState('stTalking')
      }
    }
  },
  onRegister: function (j) {},
  register: function (k, m, l) {
    return hojo.subscribe(k, m, l)
  },
  unregister: function (n) {
    hojo.unsubscribe(n)
  },
  playSound: function () {
    try {
      document.soundPlayer.play()
    } catch (e) {
      console.debug(e)
    }
  },
  stopSound: function () {
    try {
      document.soundPlayer.stop()
    } catch (e) {
      console.debug(e)
    }
  },
  _exit: function (o, d) {
    var r = './login.html'
    if (d == undefined) {
      d = true
    }
    var s = this
    if (!o) {
      o = s.loginName
    }
    var t = this.proxy_url
    var q = false
    var p = {
      Command: 'Action',
      Action: 'Logoff',
      SessionID: s.uniqueId,
      ActionID: 'Logoff' + Math.random(),
      QueueRemove: d,
      User: s.userId,
      PBX: s.pbx_in_ip,
      Account: s.accountId
    }
    hojo.io.script.get({
      url: t,
      content: {
        json: hojo.toJson(p)
      },
      callbackParamName: 'callbackName',
      timeout: 15000,
      preventCache: true,
      load: function (v, u) {
        console.debug('退出成功')
        console.dir(v)
        console.debug('清除事件XHR')
        r
      },
      error: function (v, u) {
        console.debug('注销返回错误')
        console.dir(v)
        q = true
        console.debug('清除事件XHR')
        r
      }
    })
  },
  _changeState: function (w) {
    console.debug('改变状态[%s]', w)
    hojo.publish('EvtBarChange', [this.extenType + '_' + w])
  },
  _eventHandler: function (x) {
    try {
      var s = this
      hojo.forEach(x, function (y) {
        if (s._base == null) {
          s._base = new icallcenter.stateElement.base(s)
        }
        s._base._switchState(y)
      })
    } catch (e) {
      console.dir(e)
    }
  },
  _waitEvent: function () {
    if (this._isWaitingEvent) {
      return
    }
    if (this._evtXhr == null) {
      return
    }
    this._isWaitingEvent = true
    var s = this
    var t = this.proxy_url
    var p = {
      Command: 'Action',
      Action: 'GetState',
      ActionID: 'GetState' + Math.random(),
      SessionID: this.uniqueId,
      User: this.userId
    }
    hojo.io.script.get({
      url: t,
      content: {
        json: hojo.toJson(p)
      },
      callbackParamName: 'callbackName',
      timeout: 15000,
      preventCache: true,
      load: function (v, u) {
        iccCount = 0
        s.display('')
        if (!v) {
          return
        }
        var B = v
        var z = B.Response
        if (!z) {
          z = B
        }
        if (z.Succeed && !z.HasEvent) {} else {
          if (!z.Succeed) {
            console.debug('会话失效')
            
            s._isWaitingEvent = false
            if (z.Expired) {
              console.debug('开始自动重连')
              s._relogin()
              return
            } else {
              console.debug('返回错误!')
            }
          } else {
            if (z.Kick) {
              var A = ''
              if (z.Comments) {
                A = z.Comments
              }
              if (A == 'ukick' || A == 'ekick') {
                icallcenter.hojotools.error('您当前的会话已经失效,导致该问题的原因是别的座席使用相同的帐号（或相同的分机）登录了')
              } else {
                icallcenter.hojotools.error('您当前的会话已经失效,导致该问题的原因可能是被管理员强制签出')
              }
              console.debug(z.Message)
              './notify.html'
              s.destroy()
              return
            } else {
              var C = B.Event
              if (C != null) {
                s._eventHandler(C)
              }
            }
          }
        }
        s._isWaitingEvent = false
        s._waitEvent()
      },
      error: function (v, u) {
        s._isWaitingEvent = false
        window.setTimeout(function () {
          iccCount++
          if (iccCount > 3) {
            s.display('连接服务器超时，可能是您的网络问题，正在尝试重新连接...')
          }
          s._waitEvent()
        }, 1000)
        return
      }
    })
  },
  display: function (D) {
    var E = hojo.byId('netMessage')
    if (E) {
      E.innerHTML = D
    }
  },
  _relogin: function () {
    if (this._isRelogin) {
      return
    }
    var s = this
    s._isRelogin = true
    var p = {
      Command: 'Action',
      Action: 'Login',
      ActionID: 'Login' + Math.random(),
      ExtenType: s.extenType,
      User: s.loginName,
      Password: s.password,
      AutoBusy: false,
      Monitor: s.Monitor
    }
    hojo.io.script.get({
      url: s.proxy_url,
      content: {
        json: hojo.toJson(p)
      },
      callbackParamName: 'callbackName',
      timeout: 15000,
      preventCache: true,
      load: function (v, u) {
        var z = v
        
        if (!z.Succeed) {
          var F = z.Result
          if (F) {
            if (F == 601) {
              icallcenter.hojotools.error('您的账户通话座席登录数已达最大或者已经到期,请使用无通话方式登录或联系管理员')
            } else {
              if (F == 602) {
                icallcenter.hojotools.error('您的账户无通话座席登录数已达最大或者已经到期,请使用软电话/网关/直线方式登录或联系管理员')
              } else {
                icallcenter.hojotools.error('登录失败' + F + ',请联系管理员')
              }
            }
          } else {
            icallcenter.hojotools.error('您当前的会话已经失效,导致该问题的原因可能是被管理员强制签出')
          }
          './notify.html'
          s.destroy()
        } else {
          if (z.SessionID) {
            console.debug('重新登录成功')
            s.uniqueId = z.SessionID
            var G = new Date()
            var H = G.valueOf()
            s.currentServerTime = H - z.Timestamp * 1000
            if (s._peerState._curPeerStateKey == '0') {
              s.setBusy(false, s._peerState._curPeerStateKey)
            } else {
              if (s._peerState._curPeerStateKey != '99') {
                s.setBusy(true, s._peerState._curPeerStateKey)
              }
            }
            s._waitEvent()
          } else {
            console.debug('登录成功,但没有sessionid')
          }
        }
        s._isRelogin = false
      },
      error: function (v, u) {
        console.debug('ACTION返回错误[%s]', v)
      }
    })
  },
  dialout: function (K) {
    console.debug('呼叫：' + K)
    var s = this
    var I = ''
    if (K.length < 5) {
      var J = this._base._getUserViaExten(K)
      if (!J) {
        K = '9' + K
        I = 'dialout'
        s.callObject.originCallNo = s.didNum
        s.callObject.originCalledNo = K
      } else {
        I = 'inner'
      }
    } else {
      K = '9' + K
      I = 'dialout'
      s.callObject.originCallNo = s.didNum
      s.callObject.originCalledNo = K
    }
    this._sendAction('Originate', {
      Channel: 'SIP/' + s.sipNo,
      Context: s.accountId,
      Exten: K,
      Priority: '1',
      UserID: s.userId,
      Timeout: 60000,
      Async: 'true',
      CallType: I
    }, function (v, u) {
      var L = v
      console.dir(v)
      if (L.Succeed) {
        console.debug('外呼[%s]成功', K)
      } else {
        console.debug('外呼失败')
        console.dir(L)
        if (L.Expired) {
          s._relogin()
        }
      }
    })
  },
  batchDialout: function (K, Q) {
    console.debug('批量呼叫：' + K)
    var s = this
    if (K && Q) {
      var P = Q.context
      var R = Q.type
      var O = Q.callbackSuccFun
      var M = Q.callbackFailFun
      var N = Q.callbackObj
      this._sendAction('BatchDialout', {
        BatchDialoutType: R,
        Context: P,
        CallNumber: K,
        Timeout: 120000,
        Async: 'true'
      }, function (v, u) {
        var L = v
        if (L.Succeed) {
          console.debug('批量外呼[%s]成功', K)
          O.call(N, v.Message)
        } else {
          M.call(N, 0)
        }
      }, function (v, u) {
        console.debug('批量外呼[%s]失败', K)
        M.call(N, 0)
      })
    } else {
      console.debug('批量外呼号码不存在。')
    }
  },
  playDTMF: function (S) {
    console.debug('play DTMF[%s]', S)
    sipPhone.PlayDTMF(S)
  },
  answer: function () {},
  hangup: function () {
    var s = this
    console.debug('挂断电话：' + s.extenType)
    this._sendAction('Hangup', {
      Channel: s._curChannel
    }, function (v, u) {
      var L = v
      console.dir(L)
      if (L.Succeed) {
        console.debug('挂机动作成功')
      } else {
        console.debug('挂机动作失败')
        s.callObject = {}
        if (L.Expired) {
          s._relogin()
        }
      }
    })
  },
  hold: function () {
    var s = this
    this._sendAction('Hold', {
      Channel: s._otherChannel,
      UserID: s.userId,
      Async: 'true'
    }, function (v, u) {
      var L = v
      console.dir(v)
      if (L.Succeed) {
        console.debug('保持成功')
        s._stateBeforeHold = s._base._curCallState._callState
        s._changeState('stHold')
      } else {
        console.debug('保持[%s]失败' + v.Message, s._curChannel)
        if (L.Expired) {
          s._relogin()
        }
      }
    })
  },
  unhold: function () {
    var s = this
    this._sendAction('Unhold', {
      Channel: s._otherChannel,
      UserID: s.userId,
      Async: 'true'
    }, function (v, u) {
      var L = v
      console.dir(v)
      if (L.Succeed) {
        console.debug('取消保持成功')
        s._changeState(s._stateBeforeHold)
      } else {
        console.debug('取消保持[%s]失败' + v.Message, s._curChannel)
        if (L.Expired) {
          s._relogin()
        }
      }
    })
  },
  investigate: function () {
    if (this._isInvestigatting) {
      return
    } else {
      this._isInvestigatting = true
    }
    console.info('转满意度调查')
    console.dir(this.callObject)
    var s = this
    var T = s.userId
    var P = s.accountId + '-investigate'
    s._sendAction('Transfer', {
      Exten: 's',
      Channel: s._otherChannel,
      CallType: 'investigate',
      CallType: 'investigate',
      UserID: T,
      Context: P
    }, function (v, u) {
      console.dir(v)
      var L = v
      if (L.Succeed) {
        console.debug('转满意度调查成功')
      } else {
        console.debug('转满意度调查失败')
        s._isInvestigatting = false
        if (L.Expired) {
          s._relogin()
        }
      }
    })
    this._isInvestigatting = false
  },
  transfer: function (V, X, Z) {
    var s = this
    console.info('电话转接[%s:%s]', V, X)
    var W = s.callObject.originCallNo
    if (V.substr(0, 1) == '9' && X == 'external') {
      if (V.length <= 5) {
        V = V.substr(1)
        var J = this._base._getUserViaExten(V)
        if (!J) {
          V = '9' + V
        }
      }
    }
    var Y = hojo.objectToQuery(Z)
    console.debug(Y)
    var P = ''
    P = this.accountId
    var ba
    var U
    if (s.callObject && s.callObject.data) {
      ba = s.callObject.data.workSheetId
      U = s.callObject.data.customerId
    }
    s._sendAction('Transfer', {
      WorkSheetID: ba ? ba : '',
      CustomerID: U ? U : '',
      Exten: V,
      UserID: s.userId,
      Channel: s._otherChannel,
      ExtraChannel: s._curChannel,
      Context: P
    }, function (v, u) {
      console.dir(v)
      var L = v
      if (L.Succeed) {} else {
        console.debug('转接失败-' + L.Message)
        var D = ''
        if (L.Message == '310') {
          D = '未配置外呼线路'
        } else {
          if (L.Message == '311') {
            D = '转接的用户忙'
          } else {
            if (L.Message == '312') {
              D = '转接的用户未签入'
            } else {
              if (L.Message == '313') {
                D = '转接的用户正在通话'
              } else {
                if (L.Message == '314') {
                  D = '转接的用户没有以通话方式登录'
                } else {
                  if (L.Message == '315') {
                    D = '无法呼通转接的用户'
                  } else {
                    if (L.Message == '316') {
                      D = '转接用户不存在'
                    } else {
                      D = ''
                    }
                  }
                }
              }
            }
          }
        }
        if (D == '') {
          icallcenter.hojotools.error('转接失败')
        } else {
          icallcenter.hojotools.error('转接失败：' + D)
        }
        if (L.Expired) {
          s._relogin()
        }
      }
    }, function (v, u) {
      icallcenter.hojotools.close()
      console.debug('ACTION返回错误')
      console.dir(v)
    })
  },
  phone_cancelTransfer: function () {
    var s = this
    if (s._otherChannel) {
      var p = {
        Channel: s._otherChannel
      }
      var bc = function (v) {
        icallcenter.hojotools.close()
        if (v.Succeed) {
          icallcenter.hojotools.showSucc('取消转接成功')
        } else {
          icallcenter.hojotools.error('取消转接失败')
          if (v.Expired) {
            s._relogin()
          }
        }
      }
      var bb = function () {
        icallcenter.hojotools.close()
        icallcenter.hojotools.error('取消转接失败')
      }
      s._sendAction('CancelTransfer', p, bc, bb)
    }
  },
  listen: function (bd) {
    var s = this
    if (this._peerState._curPeerStateKey == '0') {
      icallcenter.hojotools.error('请先将电话置为忙碌')
      return
    }
    this._sendAction('Originate', {
      Channel: 'SIP/' + s.sipNo,
      Application: 'ChanSpy',
      Data: bd + '|bq',
      UserID: s.userId,
      Callerid: s.sipNo,
      Async: 'true'
    }, function (v, u) {
      var L = v
      console.dir(v)
      if (L.Succeed) {
        console.debug('监听[%s]成功', bd)
        s._otherChannel = bd
      } else {
        console.debug('监听[%s]失败' + v.Message, bd)
        if (L.Expired) {
          s._relogin()
        }
      }
    })
  },
  hangupChannel: function (bd) {
    var s = this
    console.debug('强拆' + bd)
    var be = {
      Channel: bd
    }
    var bc = function (v, u) {
      console.dir(v)
      var L = v
      if (L.Succeed) {
        console.debug('强拆动作成功')
      } else {
        console.debug('强拆动作失败')
        if (L.Expired) {
          s._relogin()
        }
      }
    }
    if (this._destroyed) {
      return
    }
    var p = {}
    var t = this.proxy_url
    hojo.mixin(p, {
      Command: 'Action',
      Action: 'Hangup',
      ActionID: 'ForceHangup' + Math.random(),
      PBX: this.pbx_in_ip,
      Account: this.accountId,
      SessionID: this.uniqueId
    })
    hojo.mixin(p, be)
    if (bc == null) {
      bc = function (v, u) {
        console.debug('ACTION调用成功[%s]', v)
      }
    }
    console.debug('发送ACTION')
    console.dir(p)
    hojo.io.script.get({
      url: t,
      content: {
        json: hojo.toJson(p)
      },
      callbackParamName: 'callbackName',
      timeout: 60000,
      preventCache: true,
      load: bc,
      error: function (v, u) {
        console.debug('ACTION返回错误')
        console.dir(v)
      }
    })
  },
  lootCall: function (bd) {
    var s = this
    if (this._peerState._curPeerStateKey == '0') {
      icallcenter.hojotools.error('请先将电话置为忙碌')
      return
    }
    var P = this.accountId
    console.debug('抢接' + bd)
    s._sendAction('Transfer', {
      Exten: s.sipNo,
      Channel: bd,
      UserID: s.userId,
      CallType: 'Loot',
      Context: P
    }, function (v, u) {
      console.dir(v)
      var L = v
      if (L.Succeed) {
        console.debug('抢接成功')
        s._isLooting = true
      } else {
        console.debug('抢接失败')
        if (L.Expired) {
          s._relogin()
        }
      }
    })
  },
  kick: function (bf) {
    console.debug('签出座席' + bf)
    var s = this
    this._sendAction('Kick', {
      Exten: bf
    }, function (v, u) {
      var L = v
      console.dir(v)
      if (L.Succeed) {
        console.debug('签出[%s]成功', bf)
        var J = s.monitorPeers[bf]
        if (J) {
          J.C5Status = ''
          J.callNo = ''
          J.callStatus = 'Idle'
          var G = new Date()
          var H = G.valueOf()
          J.timestamp = H / 1000
          linked = false
          J.channel = ''
          J.linkedChannel = ''
          console.debug('kickoff')
          hojo.publish('EvtMonitorPeer', [J])
          s._base._updateQueueInfo()
        }
      } else {
        console.debug('签出[%s]失败' + v.Message, bf)
        if (L.Expired) {
          s._relogin()
        }
      }
    })
  },
  pick: function (T) {
    console.debug('签入座席' + T)
    var s = this
    var J = s.monitorPeers[T]
    if (J == null || J.localNo == null || J.localNo == '') {
      icallcenter.hojotools.error('不能对没有直线号码的座席做签入操作')
      return
    }
    this._sendAction('SignIn', {
      User: T
    }, function (v, u) {
      var L = v
      console.dir(v)
      if (L.Succeed) {
        console.debug('签入[%s]成功', T)
        icallcenter.hojotools.showSucc('座席签入成功')
      } else {
        console.debug('签入[%s]失败' + L.Message, T)
        if (L.Expired) {
          s._relogin()
        }
      }
    })
  },
  threeWayCall: function (K) {
    console.debug('开始三方通话：' + K)
    var s = this
    this._sendAction('ThreeWayCall', {
      FromExten: s.sipNo,
      Exten: K,
      UserID: s.userId,
      Timeout: 60000
    }, function (v, u) {
      var L = v
      console.dir(L)
      if (L.Succeed) {
        console.debug('三方通话[%s]成功', K)
        s._changeState('stThreeWayTalking')
      } else {
        console.debug('三方通话失败')
        if (L.Expired) {
          s._relogin()
        }
        icallcenter.hojotools.error('三方通话失败')
      }
    })
  },
  consult: function (K, X) {
    console.debug('开始咨询通话：' + K)
    var s = this
    if (K.substr(0, 1) == '9' && X == 'external') {
      if (K.length <= 5) {
        K = K.substr(1)
        var J = this._base._getUserViaExten(K)
        if (!J) {
          K = '9' + K
        }
      }
    }
    if (K.length > 4 && X != 'skillgroup') {
      icallcenter.hojotools.showLoading(K)
      fromCid = this.sipNo + '@' + this.didNum
    } else {
      if (K.length <= 4 && X != 'skillgroup') {
        if (K.substr(0, 1) != '9') {
          icallcenter.hojotools.showLoading('工号  ' + K + ' ')
        } else {
          icallcenter.hojotools.showLoading(K)
        }
      } else {
        if (X == 'skillgroup') {
          icallcenter.hojotools.showLoading(K)
        }
      }
    }
    this._sendAction('Consult', {
      FromExten: s.sipNo,
      Exten: K,
      UserID: s.userId,
      Timeout: 60000
    }, function (v, u) {
      icallcenter.hojotools.close()
      var L = v
      console.dir(L)
      if (L.Succeed) {
        console.debug('咨询[%s]成功', K)
        icallcenter.hojotools.showSucc('咨询成功')
        s._changeState('stConcultTalking')
      } else {
        icallcenter.hojotools.error('咨询失败')
        console.debug('咨询失败')
        if (L.Expired) {
          s._relogin()
        }
      }
    }, function (v, u) {
      icallcenter.hojotools.close()
      icallcenter.hojotools.error('咨询失败')
      console.debug('ACTION返回错误')
      console.dir(v)
    })
  },
  stopConsult: function () {
    console.debug('结束咨询通话')
    var s = this
    this._sendAction('StopConsult', {
      FromExten: s.sipNo,
      UserID: s.userId,
      Timeout: 60000
    }, function (v, u) {
      var L = v
      console.dir(L)
      if (L.Succeed) {
        if (v.Message != undefined) {
          if (v.Message == 'Idle') {
            s._changeState('stInvalid')
          } else {
            s._changeState('stTalking')
          }
        } else {
          s._changeState('stTalking')
        }
      } else {
        console.debug('结束咨询失败')
        if (L.Expired) {
          s._relogin()
        }
        icallcenter.hojotools.error('结束咨询通话失败')
      }
    })
  },
  setBusy: function (bh, bg) {
    if (this._isSettingbusy) {
      return
    } else {
      this._isSettingbusy = true
    }
    var s = this
    var be = {
      'Exten': s.userId,
      Busy: bh,
      BusyType: '' + bg
    }
    s._sendAction('Busy', be, function (v, u) {
      var bi = v
      if (bi.Succeed) {
        console.debug('修改状态成功')
      } else {
        if (bi.Expired) {
          s._relogin()
        }
      }
    })
    this._isSettingbusy = false
  },
  toIVR: function () {
    console.info('转IVR验证')
    var s = this
    var P = userInfo.accountId + '-validate'
    var bj = 'Validate'
    if (userInfo.accountId == 'Q000000003893' || userInfo.accountId == 'B000000006069') {
      bj = 'Check'
    }
    s._sendAction(bj, {
      Exten: 's',
      Channel: s._otherChannel,
      Context: P
    }, function (v, u) {
      console.dir(v)
      var L = v
      if (L.Succeed) {
        console.debug('转IVR成功')
      } else {
        console.debug('转IVR失败')
        if (L.Expired) {
          s._relogin()
        }
        return ERR_NO_SUCH_CHANNEL
      }
    })
    this._isInvestigatting = false
    return SUCCESS
  },
  phone_toMenu: function (bf) {
    var bj = 'IvrMenu'
    var p = {
      Channel: this._otherChannel,
      Context: bf
    }
    phone._sendAction(bj, p, function (v) {
      console.dir(v)
      if (v.Succeed) {
        console.log('来电正在转验证，请稍后')
        icallcenter.hojotools.showSucc('来电正在转验证，请稍后')
      } else {
        console.log('转IVR菜单失败')
        icallcenter.hojotools.showSucc('转IVR菜单失败')
        if (json.Expired) {
          self._relogin()
        }
      }
    }, function () {
      console.log('转IVR菜单失败')
      icallcenter.hojotools.showSucc('转IVR菜单失败')
    })
  },
  changePhone: function (bl, bk) {
    console.debug('变更登录方式[' + bl + '-' + bk + ']')
    var s = this
    if (bl == 'Local' || bl == 'gateway') {
      if (s.extenType == 'sip') {
        sipPhone.UnInitNoFire()
      }
      s.extenType = bl
      s.sipNo = bk
    } else {
      return
    }
    s._sendAction('SetExtenType', {
      User: s.userId,
      ExtenType: bl,
      LoginExten: bk
    }, function (v, u) {
      console.dir(v)
      var L = v
      if (L.Succeed) {
        console.debug('变更登录方式成功')
      } else {
        console.debug('变更登录方式失败')
        if (L.Expired) {
          s._relogin()
        }
      }
    })
  },
  _sendAction: function (bm, be, bc, bn) {
    if (this._destroyed) {
      return
    }
    var p = {}
    var t = this.proxy_url
    hojo.mixin(p, {
      Command: 'Action',
      Action: bm,
      ActionID: bm + Math.random(),
      PBX: this.pbx_in_ip,
      Account: this.accountId,
      SessionID: this.uniqueId
    })
    hojo.mixin(p, be)
    var bo = 60000
    if (be.Timeout != 'undefined') {
      bo = be.Timeout
    }
    if (bc == null) {
      bc = function (v, u) {
        console.debug('ACTION调用成功[%s]', v)
      }
    }
    if (bn == null) {
      bn = function (v, u) {
        console.debug('ACTION返回错误')
        console.dir(v)
      }
    }
    console.debug('发送ACTION')
    console.dir(p)
    hojo.io.script.get({
      url: t,
      content: {
        json: hojo.toJson(p)
      },
      callbackParamName: 'callbackName',
      timeout: bo,
      preventCache: true,
      load: bc,
      error: bn
    })
  },
  onAutoBusyTimeChanged: function (bp) {
    this.autoBusyTime = bp
  }
})
icallcenter.Phone.registerEvent = function (a) {
  var q = null
  var t = a.proxy_url
  var p = {
    Command: 'Action',
    Action: 'Login',
    ActionID: 'Login' + Math.random(),
    ExtenType: a.extenType,
    Password: a.password,
    BusyType: a.busyType,
    Monitor: a.Monitor,
    User: a.User
  }
  var bq = this
  hojo.io.script.get({
    url: t,
    content: {
      json: hojo.toJson(p)
    },
    callbackParamName: 'callbackName',
    timeout: 15000,
    preventCache: true,
    load: function (v, u) {
      var z = v
      
      if (!z.Succeed) {
        q = false
        var F = z.Result
        if (F) {
          if (F == 601) {
            icallcenter.hojotools.error('您的账户通话座席登录数已达最大或者已经到期,请使用无通话方式登录或联系管理员')
          } else {
            if (F == 602) {
              icallcenter.hojotools.error('您的账户无通话座席登录数已达最大或者已经到期,请使用软电话/网关/直线方式登录或联系管理员')
            } else {
              icallcenter.hojotools.error('登录失败' + F + ',请联系管理员')
            }
          }
        }
        bq.logonStatus = 'logonFail'
      } else {
        if (z.SessionID) {
          a.uniqueId = z.SessionID
          var G = new Date()
          var H = G.valueOf()
          a.currentServerTime = H - z.Timestamp * 1000
          a.PhonebarConfig = z.PhonebarConfig
          a.autoBusyTime = z.AutoBusyTime
          a.userId = z.UserID
          a.pbx_in_ip = z.PBX
          a.accountId = z.Account
          a.loginName = a.User
          a.sipNo = z.SipNum
          q = new icallcenter.Phone(a)
          phone = q
          icallcenter.logon.afterPhone(phone)
          bq.logonStatus = 'logonSuccess'
        } else {
          bq.logonStatus = 'logonFail'
          q = false
        }
      }
      hojo.publish('EvtLogon', [bq.logonStatus])
      return v
    },
    error: function (v, u) {
      icallcenter.hojotools.error('请求超时，请检查本地网络')
      console.debug('注册ass失败')
      console.dir(v)
      bq.logonStatus = 'logonFail'
      hojo.publish('EvtLogon', [bq.logonStatus])
      return v
    }
  })
}
